package db

import (
	"errors"
	mydb "filestore-rebuild/db/orm"
	"filestore-rebuild/models"
	"log"
	"time"
)

func CheckUsernameExistsORM(username string) bool {
	var user models.User
	db := mydb.GetDB()
	db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&models.User{})

	log.Println(user)

	return false
}

func InsertUser(username, password string) bool {
	db := mydb.GetDB()
	var user models.User

	db.Where("user_name = ?", username).First(&user)
	if user.UserName == username {
		return false
	}
	user = models.User{UserName: username, UserPwd: password, LastActive: time.Now()}
	db.Create(&user)
	return true
}

func SelectUserByUserNameAndPasswd(username, password string) (models.User, error) {
	db := mydb.GetDB()
	var user models.User
	db.Where("user_name = ?", username).First(&user)
	if user.UserName != username {
		return user, errors.New("username not found")
	}
	if user.UserPwd != password {
		return user, errors.New("password error")
	}
	user.UserPwd = ""
	return user, nil
}

func SelectUserByUserName(username string) (models.User, error) {
	db := mydb.GetDB()
	var user models.User
	db.Where("user_name = ?", username).First(&user)
	if username != user.UserName {
		return user, errors.New("user not found")
	}
	user.ID = 0
	user.UserPwd = ""
	return user, nil
}

func UpdateUser(user models.User) bool {
	var tmpUser models.User
	db := mydb.GetDB()
	db.Where("user_name = ?", user.UserName).First(&tmpUser)
	if tmpUser.UserName != user.UserName {
		return false
	}
	db.Model(&tmpUser).Updates(map[string]interface{}{
		"email": user.Email, "phone": user.Phone,
	})
	return true
}
